package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {
    @Resource
    private DishService dishService;
    @Resource
    private RedisTemplate<String, List<DishVO>> redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId 菜品分类ID
     * @return 包含菜品信息的响应结果
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        String key = "dish:category:" + categoryId;
        log.info("尝试从缓存获取菜品分类ID: {}", categoryId);

        List<DishVO> list = redisTemplate.opsForValue().get(key);

        if (list != null && !list.isEmpty()) {
            log.info("缓存命中，返回 {} 条记录", list.size());
            return Result.success(list);
        } else if (list != null) {
            // 空值缓存，防止缓存穿透
            redisTemplate.expire(key, 60, TimeUnit.SECONDS);
            return Result.success(list);
        }
        log.info("缓存未命中，查询数据库");
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品
        list = dishService.listWithFlavor(dish);
        redisTemplate.opsForValue().set(key, list, 60, TimeUnit.SECONDS);

        return Result.success(list);
    }

}
